package com.webbuilder.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.ResultSet;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webbuilder.common.Var;

public class SysUtil {
	private static long currentId = 0;
	private static char serverId;
	private static Object idLock = new Object();
	private static Object noLock = new Object();

	public static String getId() {
		long id;
		synchronized (idLock) {
			if (currentId == 0) {
				currentId = (new Date()).getTime() * 10000;
				try {
					serverId = Var.get("server.serverId").charAt(0);
				} catch (Throwable e) {
					serverId = '2';
				}
			}
			id = currentId++;
		}
		return numToString(id);
	}
	
	public static String getOrgCode(HttpServletRequest request) {
		Long id=0L;
		String parent_org_code=request.getParameter("parent_org_code");
		if(parent_org_code==null){
			parent_org_code=(String) request.getAttribute("parent_org_code");
		}
		String is_daili=request.getParameter("is_daili");
		if(is_daili==null){
			is_daili=(String) request.getAttribute("is_daili");
		}
		synchronized (noLock) {
			if(parent_org_code.equals("0")){//获取会员机构码
				try {
					int len=4;//会员是4位位机构码
					ResultSet rs=DbUtil.query(request, "select max(cast(organization_code as unsigned)) organization_code from wjy_user where LENGTH(organization_code) = "+len);
					rs.next();
					if(rs.getString(1)!=null){
						id = Long.valueOf(rs.getString(1))+1;
					}else{
						id=Long.valueOf("1000");
					}
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}else{
				if (parent_org_code.length()==4) {//父级代码是会员
					try {
						int len=9;//如果不是代理获取9位机构码,如果是代理获取6位机构码
						if(is_daili.equals("1")){
							len=6;
						}
						ResultSet rs=DbUtil.query(request, "select max(cast(organization_code as unsigned)) organization_code from wjy_user where parent_org_code='"+parent_org_code+"' and LENGTH(organization_code) = "+len);
						rs.next();
						if(rs.getString(1)!=null){
							id = Long.valueOf(rs.getString(1))+1;
						}else{
							if(len==9){
								id=Long.valueOf(parent_org_code+"00001");
							}else{
								id=Long.valueOf(parent_org_code+"01");
							}
						}
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
				if (parent_org_code.length()==6) {//父级代码是代理商
					try {
						ResultSet rs=DbUtil.query(request, "select max(cast(organization_code as unsigned)) organization_code from wjy_user where parent_org_code='"+parent_org_code+"' and LENGTH(organization_code) = 9");
						rs.next();
						if(rs.getString(1)!=null){
							id = Long.valueOf(rs.getString(1))+1;
						}else{
							id=Long.valueOf(parent_org_code+"001");
						}
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
			}
			
		}
		return id.toString();
	}

	private static char intToChar(int val) {
		if (val < 10)
			return (char) (val + 48);
		else
			return (char) (val + 55);
	}

	private static String numToString(long num) {
		char[] buf = new char[12];
		int charPos = 12;
		long val;

		buf[0] = serverId;
		while ((val = num / 36) > 0) {
			buf[--charPos] = intToChar((int) (num % 36));
			num = val;
		}
		buf[--charPos] = intToChar((int) (num % 36));
		return new String(buf);
	}

	public static String getShortError(Throwable e) {
		Throwable cause = e, c = e;

		while (c != null) {
			cause = c;
			c = c.getCause();
		}
		String message = cause.getMessage();
		if (StringUtil.isEmpty(message))
			message = cause.toString();
		return StringUtil.toLine(message);
	}

	public static void executeMethod(String classMethodName,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int pos = classMethodName.lastIndexOf('.');
		String className, methodName;

		if (pos == -1) {
			className = "";
			methodName = classMethodName;
		} else {
			className = classMethodName.substring(0, pos);
			methodName = classMethodName.substring(pos + 1);
		}
		Class<?> cls = Class.forName(className);
		cls.getMethod(methodName, HttpServletRequest.class,
				HttpServletResponse.class).invoke(cls, request, response);
	}

	public static void executeMethod(String classMethodName) throws Exception {
		if (StringUtil.isEmpty(classMethodName))
			return;
		int pos = classMethodName.lastIndexOf('.');
		String className, methodName;

		if (pos == -1) {
			className = "";
			methodName = classMethodName;
		} else {
			className = classMethodName.substring(0, pos);
			methodName = classMethodName.substring(pos + 1);
		}
		Class<?> cls = Class.forName(className);
		cls.getMethod(methodName).invoke(cls);
	}

	public static int isToOs(InputStream is, OutputStream os) throws Exception {
		byte buf[] = new byte[8192];
		int len, size = 0;

		while ((len = is.read(buf)) > 0) {
			os.write(buf, 0, len);
			size += len;
		}
		return size;
	}

	public static ByteArrayInputStream getBIS(InputStream is) throws Exception {
		if (is == null)
			return null;
		if (is instanceof ByteArrayInputStream)
			return (ByteArrayInputStream) is;
		ByteArrayOutputStream bos;
		try {
			bos = new ByteArrayOutputStream();
			SysUtil.isToOs(is, bos);
		} finally {
			is.close();
		}
		return new ByteArrayInputStream(bos.toByteArray());
	}

	public static String readString(Reader reader) throws Exception {
		char buf[] = new char[8192];
		StringBuilder sb = new StringBuilder();
		int len;

		while ((len = reader.read(buf)) > 0) {
			sb.append(buf, 0, len);
		}
		return sb.toString();
	}

	public static void closeInputStream(InputStream inputStream) {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (Throwable e) {
			}
		}
	}

	public static void error(String msg) throws Exception {
		throw new Exception(msg);
	}
	
	/**
	 * UID生成器
	 * @return
	 * @throws Exception
	 */
	public static String getUUID()throws Exception{
		String uid=UUID.randomUUID().toString();
		return uid.replace("-", "");
	}
}
